import android.util.Log
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.delay
import kotlinx.coroutines.withContext
import java.net.URL

@Composable
fun MyLaunchedEffectTest1() {
    var show by remember { mutableStateOf(true) }
    if (show) {
        Text(text = "三秒后消失")
        LaunchedEffect(key1 = Unit) {
            withContext(Dispatchers.Default){
                println("curr thread ${Thread.currentThread()}")
                delay(3000)
                show = false
            }
        }
    }
}

@Composable
fun MyScreen() {
    println("MyScreen enter")
    // 声明一个可变变量 number 保存请求返回的数字
    var number by remember { mutableStateOf(0) }

    // 使用 LaunchedEffect 在界面创建时做网络请求获取数字
    LaunchedEffect(key1 = true) {
        println("LaunchedEffect start ${Thread.currentThread()}")
        try {
            val result = withContext(Dispatchers.IO) {
                URL("https://baidu.com").openStream().bufferedReader().use { it.readText() }
            }
            number = result.toInt()
        } catch (e: Exception) {
            println(e.message)
        }
    }

    // 根据 number 设置 LazyColumn 的 items 个数
    LazyColumn {
        items(number) {
            // Item 内容
        }
    }
    println("MyScreen end")
}